// sub/user/iron-one/iron-one.js
const app = getApp();
import Toast from '../../../miniprogram/miniprogram_npm/vant-weapp/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navTabList: [],
    tabActive: 0,
    childrenList: [],
    niceList: [],

    currPage: 1,
    perPage: 10,
    isEmpty: false,
    noMore: false,
    tempShopId: '',
    cateringType:'',
    productType:'',
    productTypeValue: '',
    productTypeShow:false,//右上角显示

    rangeShow:false,//规格显示
    goodInfo:{},//点击选规格后获取的商品数据
    rangeNum:'1',//弹框内商品的数量
    selectRangeId:'0',//当前点击选择某一个规格的id，关闭规格弹框时清空
    selectRangeName:'',//当前点击选择某一个规格的名称，关闭规格弹框时清空
    shopCarList:[],//购物车列表
    cartShow:false,//购物车下面一块显示隐藏
    cartListShow:'none',//购物车上面一块列表显示隐藏
    totalCount:'0',//购物车总数量
    totalPrice:'0',//购物车总价格
  },
  onReady: function () {
    this.animation = wx.createAnimation()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    let that = this;
    let scene = event.scene;
    let tempShopId = wx.getStorageSync('tempShopId');//缓存shopId
    let shopInfo = app.getShop();
    if (scene) {
      let tt = scene.split('-');
      if (tt.length > 0) {
        let obj = {};
        tt.forEach(item => {
          obj[item.split('!')[0]] = item.split('!')[1];
        })
        console.log('productType='+obj.productType + '--cateringType='+obj.cateringType);
        // 将座位号存入缓存
        if (obj.tid) {
          tempShopId = obj.tid;
          that.setData({
            tempShopId: tempShopId,
            // 外卖类型
            productType: obj.productType,
            //餐饮类型
            cateringType: obj.cateringType
          });
          if (obj.productType == '6' && obj.cateringType == '1') {
            that.setData({
              productTypeValue: '堂食点单',
            })
          } else if(obj.productType == '6' && obj.cateringType == '3'){
            that.setData({
              productTypeValue: '到店自提',
              productType: '6',
              cateringType: obj.cateringType,
            })
          } else{
            that.setData({
              productTypeValue: '外卖点单',
              productType: '6',
              cateringType: obj.cateringType,
            })
          }
          wx.setStorageSync("seatNum-" + that.data.tempShopId, obj.seatNum);
          // wx.setStorageSync("clerkId-" + that.data.tempShopId, obj.clerkId);
          // 校验本地缓存shopinfo是否有值，如果有值则根据shopid替换shopinfo的数据，如果没值则取地址list第一条数据
          if (shopInfo) {
            // 如果不对等，则调接口覆盖数据，如果对等，则shopinfo不变
            if (tempShopId != shopInfo.id) {
              that.getShopInfo(tempShopId);
            } else {
              that.setData({
                shopInfo: shopInfo
              })
            }
          } else {
            that.getShopInfo(tempShopId);
          }
          wx.setStorageSync('tempShopId', that.data.tempShopId);
        }
      }
    } else {
      console.log(event);
      that.setData({
        tempShopId: tempShopId,
        shopInfo: app.getShop(),
        productType: '6',
        cateringType: event.cateringType
      });
      if(event.cateringType == '1'){
        that.setData({
          productTypeValue: '扫码堂食',
        })
      }else if(event.cateringType == '2'){
        that.setData({
          productTypeValue: '外卖点单',
        })
      }else{
        that.setData({
          productTypeValue: '到店自提',
        })
      }
    }
  },
  getShopInfo(val) {
    let that = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/newNearest',
      data: {
        mid: val,
        longitude: '112.98626',
        latitude: '28.25591',
        limit: 50,
        centreId: app.globalData.loginCentreId,
        flag: 2//1平台 2商户
      },
      load: 1
    }).then((res) => {
      that.setData({
        shopInfo: res.data.data[0]
      });
      wx.setStorageSync('shopInfo', JSON.stringify(res.data.data[0]));
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getNavTab();
  },


  //获取tab
  getNavTab() {
    let _this = this;
    let user = app.getUser();

    app.requestUrl({
      method: 'GET',
      url: '/wxapi/category',
      data: {
        parentid: 0,
        type:5,
        centreId: app.globalData.loginCentreId
      },
      load: 1
    }).then((res) => {
      let list = _this.makeTree(res.data.data);
      _this.setData({
        navTabList: list,
        childrenList: list[_this.data.tabActive].categoryList,
      })

      if (_this.data.childrenList.length <= 0)
        this.getNiceList(false);

    })
  },
  //处理tab数据
  makeTree(data) {
    let tree = {};
    data.forEach(item => {
      if (item.enabled && (item.status === 1)) {
        tree[item.id] = item;
      }
    });

    data.forEach(item => {
      if (item.enabled && (item.status === 1) && (item.parentid > 0)) {
        let parent = tree[item.parentid];

        if (parent) {
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(item);
        }
      }
    });

    return data.filter(item => (item.parentid === 0) && ((item.enabled && (item.status === 1))));
  },

  //商品列表
  getNiceList(isPage) {
    let _this = this;
    let tShopId = wx.getStorageSync('tempShopId');
    let tCentreId = wx.getStorageSync('tempCentreId');
    let user = app.getUser();
    let categoryId = this.data.navTabList[this.data.tabActive].id;
    if (!isPage) _this.setData({ currPage: 1 })

    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/products',
      data: {
        centreId: app.globalData.loginCentreId,
        liansuoid: app.getShop().id,//未登录需要传门店id
        teamId: app.getShop().id,//未登录需要传门店id
        mid: user.id ? user.id : '',
        isTeam: '',
        title: '',
        isKuaidi: '',
        categoryId: categoryId,//分类id
        isSpellgroup: '',//拼团商品
        ismiaosha: '',
        ishot: '',
        isvip: '',
        productType: _this.data.productType,
        offset: (_this.data.currPage - 1) * _this.data.perPage,
        limit: _this.data.perPage
      },
      load: 1
    }).then((res) => {
      var tempList = res.data.data.rows
      tempList.forEach(item =>{
        if(!item.count || item.count == ''){
          item.count = 0;
        };
     });
      if (isPage) {//下一页的数据拼接在原有数据后面
        _this.setData({ niceList: _this.data.niceList.concat(tempList) })
      }
      else {//第一页数据直接赋值
        _this.setData({
          niceList: tempList,
          isEmpty: !tempList.length > 0,
          noMore: false,
        })
      }
      //如果返回的数据为空，那么就没有下一页了
      if (tempList.length == 0) _this.setData({ noMore: true })
      console.log(_this.data.niceList);
    })
  },

  navListScrolltolower() {
    if (!this.data.noMore) {
      this.setData({ currPage: this.data.currPage + 1 })
      this.getNiceList(true)//传true代表进行下一页
    }
  },

  tabChange(event) {
    let index = event.currentTarget.dataset.index;
    let tabList = this.data.navTabList;
    this.setData({ tabActive: index, childrenList: tabList[index].categoryList || [], isEmpty: false });

    if (this.data.childrenList.length <= 0)
      this.getNiceList(false);
  },

  //二级分类
  toClassifyChildren(event) {
    let id = event.currentTarget.dataset.id;
    let name = event.currentTarget.dataset.name;
    wx.navigateTo({ url: '/pages/classify/classify-children/classify-children?id=' + id + '&name=' + name })
  },
  // 点击右上角打开弹框
  showProductTypeFunction() {
    this.setData({ productTypeShow: true });
  },

  closeProductTypeFunction() {
    this.setData({ productTypeShow: false });
  },
  // 点击选择是堂食还是外卖
  selectProductType(e){
    let that = this;
    if(e.currentTarget.dataset.cateringtype == '1'){//堂食，进入扫码点单
      // 允许从相机和相册扫码
      wx.scanCode({
        success: (res) => {
          var result = res.result;
          wx.redirectTo({
            url: res.path
          })
        }
      })
    }else if(e.currentTarget.dataset.cateringtype == '2'){//外卖
      that.setData({
        productType:e.currentTarget.dataset.type,
        cateringType:e.currentTarget.dataset.cateringtype,
        productTypeShow:false,
        productTypeValue: '外卖点单',
      });
      // this.getNiceList(false);
      this.toEnclosure(e.currentTarget.dataset.cateringtype);
    }else{
      that.setData({
        productType:e.currentTarget.dataset.type,
        cateringType:e.currentTarget.dataset.cateringtype,
        productTypeShow:false,
        productTypeValue: '到店自提',
      });
      // this.getNiceList(false);
      this.toEnclosure(e.currentTarget.dataset.cateringtype);
    }
  },

  //附近门店
  toEnclosure(cateringtype) {
    wx.redirectTo({
      url: '/subIndex/index/enclosure/enclosure?cateringType='+cateringtype
    })
  },
  // 显示规格
  showRangeFunction:function(e){
    this.setData({ rangeShow: true,goodInfo:e.currentTarget.dataset.good });
  },
  // 关闭规格
  closeRangeFunction:function(){
    this.setData({ rangeShow: false });
  },
  // 选择规格
  selectRangeFunction:function(e){
    this.setData({
      selectRangeId:e.currentTarget.dataset.id,
      selectRangeName:e.currentTarget.dataset.name
    })
  },
  // 弹框内商品的加减
  HZL_jian:function(){
    let that = this;
    let rangeNum = that.data.rangeNum;
    rangeNum -- ;
    if(rangeNum <= 1){
      rangeNum = 1;
    };
    that.setData({
      rangeNum:rangeNum
    })
  },
  HZL_jia:function(){
    let that = this;
    let rangeNum = that.data.rangeNum;
    rangeNum ++ ;
    that.setData({
      rangeNum:rangeNum
    })
  },
  // 弹框内加入购物车
  addCart:function(){
    let that = this;
    let addCartInfo = {};
    if(that.data.selectRangeId == '0'){
      Toast('请选择规格');
      return;
    }else{
      // 赋值购物车列表里的对象
      addCartInfo.vipprice = that.data.goodInfo.vipprice;
      // 单个价格
      addCartInfo.marketprice = that.data.goodInfo.marketprice;
      addCartInfo.selectRangeId = that.data.selectRangeId;
      addCartInfo.selectRangeName = that.data.selectRangeName;
      addCartInfo.count = that.data.rangeNum;
      addCartInfo.productId = that.data.goodInfo.id;
      addCartInfo.productName = that.data.goodInfo.title;
      // 单个商品下总价格
      // addCartInfo.totalProductPrice = addCartInfo.productprice * addCartInfo.count;
      if(that.data.goodInfo.vipprice && that.data.goodInfo.isvip){
        addCartInfo.totalProductPrice = that.data.rangeNum * that.data.goodInfo.vipprice;
      }else{
        addCartInfo.totalProductPrice = that.data.rangeNum * that.data.goodInfo.marketprice;
      };
      if(that.data.shopCarList.length > 0){
        // 如果购物车列表内已存在当前商品，则将列表内的数据进行更新
        that.data.shopCarList.forEach(function (item,index) {
          if(item.productId == addCartInfo.productId){
            item.count = Number(item.count)+Number(addCartInfo.count);
            // item.vipprice = item.vipprice * item.count;
            // 单个商品下总价格
            // item.totalProductPrice = item.productprice * item.count;
            if(that.data.goodInfo.vipprice && that.data.goodInfo.isvip){
              item.totalProductPrice = item.count * item.vipprice;
            }else{
              item.totalProductPrice = item.count * item.marketprice;
            };
          }else{
            that.data.shopCarList.push(addCartInfo);
          }
        });
        that.setData({
          shopCarList:that.data.shopCarList
        });
      }else{
        that.data.shopCarList.push(addCartInfo);
      };
      that.setData({ rangeShow: false });
      that.getRepareList();
    };
    that.getTotal();
  },
  //购物车列表与商品列表做比较
  getRepareList:function(){
    let that = this;
    if(that.data.shopCarList.length > 0 && that.data.shopCarList){
        that.data.shopCarList.forEach(function (cart) {
          that.data.niceList.forEach(function (good) {
          if(good.id == cart.productId){
            good.count = cart.count
          }else{
            
          }
        });
      });
    }else{
      that.data.niceList.forEach(function (good) {
        good.count = 0
      });
    }
    that.setData({
      niceList:that.data.niceList,
      cartShow:true,
      shopCarList:that.data.shopCarList,
      goodInfo:'',
      selectRangeId:'0',
      selectRangeName:'',
      rangeNum:'1',
    });
  },
  // 购物车列表显示隐藏
  cartListShowFunction:function(){
    let that = this;
    console.log(that.data.shopCarList);
    if(that.data.cartListShow == 'none'){
      // this.animation.translate(0, -354
      //   ).step();
      that.setData({
        cartListShow:'block',
        // animation: this.animation.export()
      })
    }else{
      // this.animation.translate(0, 300).step();
      that.setData({
        cartListShow:'none',
        // animation: this.animation.export()
      })
    }
  },
  // 计算总价格和总数量
  getTotal:function(){
    let that = this;
    let shopCarList = that.data.shopCarList;
    console.log(shopCarList);
    let totalCount = 0;
    let totalPrice = 0;
    that.data.shopCarList.forEach(function (item) {
      totalCount = Number(totalCount)+Number(item.count);
      totalPrice = Number(totalPrice)+Number(item.totalProductPrice);
      // if(that.data.goodInfo.vipprice && that.data.goodInfo.isvip){
      //   console.log(Number(item.count));
      //   console.log(Number(item.vipprice));
      //   that.setData({
      //     totalPrice:Number(totalPrice)+Number(item.count) * Number(item.vipprice),
      //   });
      // }else{
      //   that.setData({
      //     totalPrice:Number(totalPrice)+Number(item.count) * Number(item.marketprice),
      //   });
      // }
    });
    that.setData({
      totalCount:totalCount,
      totalPrice:totalPrice.toFixed(2),
    });
    if(that.data.shopCarList.length == 0){
      that.setData({
        cartListShow:'none',
      });
      setTimeout(function(){
        that.setData({
          cartShow:false
        })
      },100);
    }
    that.getRepareList();
  },
  // 购物车列表内加减
  car_jian:function(e){
    let that = this;
    let shopCarList = that.data.shopCarList;
    let index = e.currentTarget.dataset.index;
    shopCarList[index].count -- ;
    // shopCarList[index].totalProductPrice = shopCarList[index].productprice * shopCarList[index].count;
    if(shopCarList[index].vipprice){
      shopCarList[index].totalProductPrice = (shopCarList[index].vipprice * shopCarList[index].count).toFixed(2);
    }else{
      shopCarList[index].totalProductPrice = (shopCarList[index].marketprice * shopCarList[index].count).toFixed(2);
    };
    if(shopCarList[index].count < 1){
      shopCarList[index].count = 0;
      that.data.niceList.forEach(function (good) {
        if(good.id == shopCarList[index].productId){
          good.count = 0
        }
      });
      shopCarList.splice(index,1);
    };
    that.setData({
      shopCarList:shopCarList,
    })
    that.getTotal();
  },
  // 购物车列表内加
  car_jia:function(e){
    let that = this;
    let shopCarList = that.data.shopCarList;
    let index = e.currentTarget.dataset.index;
    shopCarList[index].count ++ ;
    // shopCarList[index].totalProductPrice = shopCarList[index].productprice * shopCarList[index].count;
    if(shopCarList[index].vipprice){
      shopCarList[index].totalProductPrice = (shopCarList[index].vipprice * shopCarList[index].count).toFixed(2);
    }else{
      shopCarList[index].totalProductPrice = (shopCarList[index].marketprice * shopCarList[index].count).toFixed(2);
    };
    that.setData({
      shopCarList:shopCarList,
    })
    that.getTotal();
  },
  // 清空购物车
  clearCarList:function(){
    let that = this;
    that.setData({
      shopCarList:[],
    });
    that.getTotal();
  },
  // 结算
  goSubmit:function(){
    let that = this;
    let shopCarList = that.data.shopCarList;
    console.log(shopCarList);
    let order = {};
    order.cartItems = [];
    shopCarList.forEach(function (item) {
      let submitInfo = {};
      submitInfo.productId = item.productId;
      submitInfo.skuTitle = item.selectRangeName;
      submitInfo.skuId = item.selectRangeId;
      submitInfo.total = 1;
      submitInfo.marketprice = item.marketprice;
      submitInfo.vipprice = item.vipprice;
      order.cartItems.push(submitInfo);
    });
    wx.setStorageSync('order', JSON.stringify(order))
      wx.navigateTo({
        url: '/pages/index/place-order-entity/place-order-entity' +
        '?isSpellgroup='+ '' + '&promoter=' + '' + '&sgorderId=' + ''
        +'&productType='+ that.data.productType + '&cateringType='+that.data.cateringType
      })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})